import java.io.*;
import java.util.ArrayList;

/**
 * User: rmikhaylenko mirusnet@gmail.com
 * Date: 14/05/13
 * Time: 14:27
 */

public class Mplayer {
    private static final String jmplayer_base_dir = System.getenv("USERPROFILE") + "\\jmplayer";

    public static void createPlaylist(String playlist_filename, String dirname) {
        FilesUtils.create_playlist_dir(jmplayer_base_dir);
        FilesUtils.makeplaylist(dirname, jmplayer_base_dir + "\\" + playlist_filename);
        FilesUtils.sortplaylist(jmplayer_base_dir + "\\" + playlist_filename);
    }

    public static void askTime(Process p) {
        PrintStream mplayerIn = new PrintStream(p.getOutputStream());
        mplayerIn.print("pausing_keep get_property time_pos\n");
        mplayerIn.flush();
    }

    public static void runMplayer(String playlist_name, long minutes) {
        String full_playlist_path = jmplayer_base_dir + "\\" + playlist_name;

        Shutdown.setShutdownTime(minutes);
        Process p;
        ReadInThread readInThread;

        ArrayList<String> list = FilesUtils.getPlaylist(full_playlist_path);

        for (String line : list) {
            FilesUtils.checkfileavailability(MplayerLine.getFilePath(line));
            System.out.println(MplayerLine.getShortFileInfo(line));
            try {
                p = Runtime.getRuntime().exec(MplayerLine.getExecLine(line));
                readInThread = new ReadInThread(p, MplayerLine.getFilePath(line), full_playlist_path);
                readInThread.start();

                while (readInThread.isAlive()) {
                    Mplayer.askTime(p);
                    Shutdown.showAlert(Shutdown.getShutdownTime());
                    Shutdown.shutdown(Shutdown.getShutdownTime());
                    Thread.sleep(30000);
                }
            } catch (InterruptedException | IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void show_playlist() {
        File dir_name = new File(jmplayer_base_dir);
        if (!dir_name.isDirectory()) {
            System.out.println("*** Unable to enter to the playlist dir " + jmplayer_base_dir);
            System.exit(1);
        }
        File[] files = dir_name.listFiles();
        if (files != null) {
            System.out.println("Playlists: ");
            for (File f : files) {
                System.out.println("\t\t" + f.getName());
            }
        }
    }
}
